#include "WatchDog.h"
#include "Util.h"

#include <tlhelp32.h>

bool WatchDog::WatchFor45Minutes( void )
{
	const size_t MaxTick = 45 * 60;
	size_t TickCount = 0;

	for( ; TickCount != MaxTick; TickCount ++, Sleep( 1000 ) )
	{
		if( WatchDog::FoundMaple( ) != NULL )
			printf( "\t\t%i seconds left - do not close Maple...\n", MaxTick - TickCount );
		else
			break;
	}
	
	if( TickCount < MaxTick )
		return false;

	if( !TerminateProcess( WatchDog::FoundMaple( ), 0 ) )
		printf("\t\tFailed to terminate MS process!\n");
	return true;
}

HANDLE WatchDog::FoundMaple( void )
{
	PROCESSENTRY32		ProcessEntry32 = { NULL };
	HANDLE				SnapshotHandle = NULL;
	HANDLE				ProcessHandle = NULL;
	
	ProcessEntry32.dwSize = sizeof( PROCESSENTRY32 );
	
	SnapshotHandle = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL );
	if( Process32First( SnapshotHandle, &ProcessEntry32 ) == TRUE )
		while( Process32Next( SnapshotHandle, &ProcessEntry32 ) == TRUE )
			if( _stricmp( ProcessEntry32.szExeFile, "MapleStory.exe" ) == 0 )
				ProcessHandle = OpenProcess( PROCESS_ALL_ACCESS, NULL, ProcessEntry32.th32ProcessID );
				
	CloseHandle( SnapshotHandle );
	return ProcessHandle;
}

bool WatchDog::LaunchMaple( void )
{
	STARTUPINFO				StartUpInfo;
	PROCESS_INFORMATION		ProcessInformation;
	
	ZeroMemory( &StartUpInfo, sizeof( StartUpInfo ) );
	StartUpInfo.cb = sizeof( StartUpInfo );
	ZeroMemory( &ProcessInformation, sizeof( ProcessInformation ) );
	
	///////////////////////////////////////////////////////////////For GMS, its GameLauncher.exe
	if( !CreateProcess( std::string( Util::GetCurDirectory( ) + "MapleStory.exe" ).c_str( ),
						NULL,
						NULL,
						NULL,
						FALSE,
						NULL,
						NULL,
						NULL,
						&StartUpInfo,
						&ProcessInformation )
						) { return false; }
	
	WaitForSingleObject( ProcessInformation.hProcess, INFINITE );
	CloseHandle( ProcessInformation.hProcess );
	CloseHandle( ProcessInformation.hThread );

	HWND GameLauncherWindowHandle = FindWindow( "StartUpDlgClass", "MapleStory" );

	while( FindWindow( "StartUpDlgClass", "MapleStory" ) )
	{
		SendMessage( FindWindowEx( GameLauncherWindowHandle, NULL, "Button", "Play!" ), WM_LBUTTONDOWN, 1, 1 );
		SendMessage( FindWindowEx( GameLauncherWindowHandle, NULL, "Button", "Play!" ), WM_LBUTTONUP, 1, 1 );
		Sleep( 10 );
	}

	return true;
}